<?php
class InstantMessage extends ORDataObject{
	var $message_id ='';
	var $sender = '';
	var $recipient_id = '';
	var $recipient_status = '';
	var $sender_status = '';
	var $message = '';
	var $root_message_id = '';
	var $date = '';
	var $emergency_id = '';
	var $dateformat = 'd-m-Y H:i:s';
	
	var $_table = 'instant_message';
	var $_key = 'message_id';
	var $_internalName = 'InstantMessage';
	
	function InstantMessage(){
		parent::ORDataObject();
	}
	
	public function addNewInstantMessage($content, $sender, $recipientId, $emergencyId, $rootMessageId = 0){
		$data = array (
			'sender' 			=> $sender,
			'message'			=> $content,
			'recipient_id'		=> $recipientId,
			'recipient_status'	=> 'new',
			'sender_status'		=> 'exist',
			'emergency_id'		=> $emergencyId
		);		
		$this->populateArray($data);		
		$this->persist();
		if ($rootMessageId == 0) $rootMessageId = $this->message_id;
		$sql = "UPDATE instant_message SET date = NOW(), root_message_id =  $rootMessageId WHERE message_id = $this->message_id";
		$this->_execute($sql);
		return $this->message_id;
	}
	
	public function getAllMessagesInbox($receiver){
		$ds = new Datasource_sql();		
		$sql = array(
			'cols' 		=> "message_id, message, DATE_FORMAT(date,'". L10nHelper::getSqlDateFormat('YmdHi')."') AS date,
							sender AS user_id, recipient_status AS status, emergency_id AS emergency,
							root_message_id AS root, username",
			'from' 		=> "$this->_table INNER JOIN user ON (sender = user_id)", 	
			'where'		=> "recipient_id = '".$receiver."' AND recipient_status <> 'deleted'",
			'orderby' 	=> "date DESC"
			);
	
		$ds->setup($this->_db,$sql);	
		return $ds->toArray();			
	}
	
	public function getAllMessagesOutbox($sender){
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "message_id, message, DATE_FORMAT(date,'". L10nHelper::getSqlDateFormat('YmdHi')."') AS date,
							recipient_id AS user_id, 'exist' AS status, emergency_id AS emergency,
							root_message_id AS root, username",
			'from' 		=> "$this->_table INNER JOIN user ON (recipient_id = user_id)",
			'where'		=> "sender = '".$sender."' AND sender_status = 'exist'",
			'orderby' 	=> "date DESC"
			);
	
		$ds->setup($this->_db,$sql);	
		return $ds->toArray();			
	}	
	
	public function deleteInboxMessage($messageId){
		// Delete in message_recipient table
		$sql = "UPDATE $this->_table SET recipient_status = 'deleted' WHERE message_id = $messageId";
		$this->_execute($sql);
		$this->purgeMessageRecipientItem();
	}
	
	public function deleteOutboxMessage($messageId){
		// Delete in instant_message table
		$sql = "UPDATE $this->_table SET sender_status = 'deleted' WHERE message_id = $messageId";
		$this->_execute($sql);	
		$this->purgeMessageRecipientItem();	
	}
	
	public function purgeMessageRecipientItem(){
		// If sender and recipient on an item already delete it, purge this item from message_recipient table
		$sql = "DELETE FROM $this->_table
				WHERE recipient_status = 'deleted' AND sender_status = 'deleted'";
		$this->_execute($sql);
	}
	
	public function markAsRead($messageId) {
		$sql = "UPDATE $this->_table SET recipient_status = 'read' WHERE  message_id = $messageId";
		$this->_execute($sql);
	}
	
	public function getAllUserImages() {
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "user_id, username",
			'from' 		=> "user",
			'where'		=> "NOT (username LIKE '%_admin' OR username LIKE 'admin')",
			'orderby' 	=> "username ASC"
		);
		$ds->setup($this->_db, $sql);
		return $ds->toArray();		
	}
	
	public function getFavouriteMap($userId) {
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "mfm.msg_favourite_map_id id, u.user_id, u.username",
			'from' 		=> "user u INNER JOIN msg_favourite_map mfm ON mfm.mapped_user_id = u.user_id",
			'where'		=> "mfm.user_id = $userId",
			'orderby' 	=> "u.username ASC",
			'limit'		=> "5"
		);
		$ds->setup($this->_db, $sql);
		return $ds->toArray();		
	}
	
	function getNewMessageNumber($userId){
		$sql = "SELECT count(message_id) as number FROM $this->_table	
				WHERE recipient_id = $userId AND recipient_status = 'new'";
		$result = $this->_execute($sql);
		return $result->fields['number'];			
	}
	
	function getNewestMessage($userId){
		$ds = new Datasource_sql();
		$sql = "SELECT u.username AS sender, im.message
				FROM $this->_table im INNER JOIN user u ON im.sender = u.user_id	
				WHERE im.recipient_id = $userId AND im.recipient_status = 'new'
				ORDER BY im.message_id DESC LIMIT 1";
		$result = $this->_execute($sql);	
		$resultArr = array (
			'value' => 0,
			'sender' => '',
			'message' => ''
		);
		if (!$result->EOF) {
			$resultArr['value'] = 1;
			$resultArr['sender'] = $result->fields['sender'];
			$resultArr['message'] = $result->fields['message'];
		}
		return $resultArr;
	}
	
	public function getConversationInbox($rootMessageId) {
		$ds = new Datasource_sql();
		$sql = array(
			'cols' 		=> "message_id, message, DATE_FORMAT(date,'". L10nHelper::getSqlDateFormat('YmdHi')."') AS date,
							sender, recipient_status as status, emergency_id as emergency, username",
			'from' 		=> "$this->_table INNER JOIN user ON (sender = user_id)", 	
			'where'		=> "root_message_id = $rootMessageId",
			'orderby' 	=> "date DESC"
			);
	
		$ds->setup($this->_db,$sql);	
		return $ds->toArray();
	}
}
?>